package es.uc3m.setichat.android.activity;

import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import es.uc3m.setichat.android.R;
import es.uc3m.setichat.android.SeTIChatService;
import es.uc3m.setichat.android.activity.SeTIChatContactsActivity.SeTIChatContactsFragment;
import es.uc3m.setichat.android.activity.SeTIChatConversationsActivity.SeTIChatTitlesFragment;
import es.uc3m.setichat.android.activity.SeTIChatSettingsActivity.PrefsFragment;


/**
 * Main activity in charge of starting the service and rendering the tab view.
 * 
 * In other embodiment will also start a login/register activity when necessary. 
 * 
 * @author Guillermo Suarez de Tangil <guillermo.suarez.tangil@uc3m.es>
 * @author Jorge Blasco Alis <jbalis@inf.uc3m.es>
 */

public class SeTIChatActivity extends Activity {

	private boolean DEBUG = false;

    //private SeTIChatService mBoundService;
    private ActionBar bar;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
                
        ProgressDialog dialog = ProgressDialog.show(this, "", "Starting...",
                true);

        dialog.show();
        
		//For debuggers
		DEBUG  = getText(R.string.debug).toString().compareTo("true") == 0?true:false;
		Log.v("SeTIChatActivity", "onCreate: Starting activity...");
		
		bar = getActionBar();
		bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);

		ActionBar.Tab contacts = bar.newTab();
		contacts.setText(getText(R.string.seti_chat_tab_scontacts));
		contacts.setTabListener(new TabListener<SeTIChatContactsFragment>(dialog, this,
				"contacts", SeTIChatContactsFragment.class));
		bar.addTab(contacts);

		ActionBar.Tab chats = bar.newTab();
		chats.setText(getText(R.string.seti_chat_tab_chat));
		chats.setTabListener(new TabListener<SeTIChatTitlesFragment>(dialog, this, "chats",
				SeTIChatTitlesFragment.class));
		bar.addTab(chats);

		
		 ActionBar.Tab settings = bar.newTab(); 
		 settings.setText(getText(R.string.seti_chat_tab_settings));
		 settings.setTabListener(new TabListener<PrefsFragment>(dialog,this,
		 "settings", PrefsFragment.class)); bar.addTab(settings);
		 

		if (savedInstanceState != null) {
			bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
		}
		
        try{

    		if(DEBUG)
    			Log.d("SeTIChatActivity", "Starting the service");
        
	        // Make sure the service is started.  It will continue running
	        // until someone calls stopService().  The Intent we use to find
	        // the service explicitly specifies our service component, because
	        // we want it running in our own process and don't want other
	        // applications to replace it.
	        startService(new Intent(SeTIChatActivity.this,
	                SeTIChatService.class));
	        
	        
        }catch(Exception e){
    		if(DEBUG)
    			Log.d("SeTIChatActivity", "Unknown Error while starting the service", e);
    		
    		//If service can't be started: show an error message and stop the service
    		
	        stopService(new Intent(SeTIChatActivity.this,
	                SeTIChatService.class));

            setContentView(R.layout.error);
	        finish();
	        return;
        }
          
    }

   
	@Override
	protected void onStart() {
		
		Log.v("SeTIChatActivity", "onStart: Starting activity...");
		super.onStart();
	}


	@Override
	protected void onResume() {
		
		Log.v("SeTIChatActivity", "onResume: Resuming activity...");
        
        try{
        
	        // Make sure the service is started.  It will continue running
	        // until someone calls stopService().  The Intent we use to find
	        // the service explicitly specifies our service component, because
	        // we want it running in our own process and don't want other
	        // applications to replace it.
	        startService(new Intent(SeTIChatActivity.this,
	                SeTIChatService.class));
	        
        }catch(Exception e){

    		if(DEBUG)
    			Log.d("SeTIChatActivity", "Unknown Error", e);

	        stopService(new Intent(SeTIChatActivity.this,
	                SeTIChatService.class));
        }
		
		super.onResume();
	}


	@Override
	protected void onDestroy() {
		
        Log.v("SeTIChatActivity", "onDestroy: Destroying activity...");
		
        // Cancel a previous call to startService().  Note that the
        // service will not actually stop at this point if there are
        // still bound clients.
        stopService(new Intent(SeTIChatActivity.this,
                SeTIChatService.class));
		
		super.onDestroy();
	}
	
	@Override
	protected void onPause() {
        Log.v("SeTIChatActivity", "onPause: Pausing activity...");
		super.onPause();
	}
    
	
	@Override
	protected void onStop() {
        Log.v("SeTIChatActivity", "onStop: Stoping activity...");
		super.onStop();
	}
    
	

	public static class TabListener<T extends Fragment> implements
			ActionBar.TabListener {
		private final Activity mActivity;
		private final String mTag;
		private final Class<T> mClass;
		private final Bundle mArgs;
		private Fragment mFragment;

		public TabListener(ProgressDialog dialog, Activity activity, String tag, Class<T> clz) {
			this(dialog, activity, tag, clz, null);
		}

		public TabListener(ProgressDialog dialog, Activity activity, String tag, Class<T> clz,
				Bundle args) {
			mActivity = activity;
			mTag = tag;
			mClass = clz;
			mArgs = args;

			// Check to see if we already have a fragment for this tab, probably
			// from a previously saved state. If so, deactivate it, because our
			// initial state is that a tab isn't shown.
			mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
			if (mFragment != null && !mFragment.isDetached()) {
				FragmentTransaction ft = mActivity.getFragmentManager()
						.beginTransaction();
				ft.detach(mFragment);
				ft.commit();
			}
			
			dialog.dismiss();
		}

		public void onTabSelected(Tab tab, FragmentTransaction ft) {
			if (mFragment == null) {
				mFragment = Fragment.instantiate(mActivity, mClass.getName(),
						mArgs);
				ft.add(android.R.id.content, mFragment, mTag);
			} else {
				ft.attach(mFragment);
			}
		}

		public void onTabUnselected(Tab tab, FragmentTransaction ft) {
			if (mFragment != null) {
				ft.detach(mFragment);
			}
		}

		public void onTabReselected(Tab tab, FragmentTransaction ft) {
			Toast.makeText(mActivity, "Reselected!", Toast.LENGTH_SHORT).show();
		}
	}
    
    
}